<?php
// 本类由系统自动生成，仅供测试用途
class GoodsAction extends BaseAction {

    public function _initialize()
    {
        parent::_initialize();
        $this->assign('sortarr',D('Goods')->getSortarr());
        $this->assign('categray',D('Goods')->getCategray());
    }

    public function index(){
    	//$map['status'] = 1;
        $type = $query['type'] = $this->_post('type','-1');
        $sort = $query['sort'] = $this->_post('sort');
        $keywords = $this->_post('keywords','htmlspecialchars');
        $keywords = $query['keywords'] = trim($keywords);
        switch ($type) {
            case '1':
                $map['sncode'] = $keywords;
                break;
            case '2':
                $map['title'] = array('like', '%'.$keywords.'%');
                break;
            default:
                break;
        }
        if(isset($sort) &&  $sort!='') {
            $map['sort'] = intval($sort);
        }
    	import('ORG.Util.Page');// 导入分页类
    	$count      = M('Goods')->where($map)->count();// 查询满足要求的总记录数 $map表示查询条件
    	$Page       = new Page($count);// 实例化分页类 传入总记录数
    	$show       = $Page->show();// 分页显示输出

		$list = M('Goods')->where($map)->limit($Page->firstRow,$Page->listRows)->order('id desc')->select();
		$this->assign('list',$list);
		$this->assign('page',$show);// 赋值分页输出
        $this->assign('query',$query);

        $this->assign('isAdmin',$this->userinfo['roleid']==1 ? true : false);
		$this->display();
    }

    public function set()
    {
        //不是管理员跳转
        if(!$this->checkIsAdmin()){
            redirect(U('Admin/Goods/index'));
        }
    	if(IS_POST){
    		$id = $this->_post('id',0);
    		$data = array();
    		if($id){
                if($this->update()){
                    $this->_success('修改成功');
                }else{
                    $this->_error('修改失败');
                }
    		}else{
    			
    			if($this->insert()){
    				$this->_success('添加成功');
    			}else{
    				$this->_error('添加失败');
    			}
    		}
    	}else{
    		$this->display();
    	}
    }
    /**
     * 删除
     * @return [type] [description]
     */
    public function del(){
        //不是管理员跳转
        if(!$this->checkIsAdmin()){
            redirect(U('Admin/Goods/index'));
        }
        $id = $this->_get('id',0);
        if($id){
            $row = M('Goods')->where(array('id'=>$id))->field('id,parent_id')->find();
            $del_id = $row['parent_id'] ? $row['parent_id'] : $row['id'];
            //把父类以及同胞类都删掉
            $re = M('Goods')->where("`id`='$del_id' OR `parent_id`='$del_id'")->delete();
            if($re){
                $this->_success('删除成功');
            }else{
                $this->_error('删除失败');
            }
        }else{
            $this->_error('删除失败');
        }
    }

    /**
     * 克隆商品
     */
    public function clone1()
    {
        //不是管理员跳转
        if(!$this->checkIsAdmin()){
            redirect(U('Admin/Goods/index'));
        }
        $id = $this->_get('id',0);
        $num = $this->_get('num',1);
        if($id && $num){
            if($num>100){
                $this->_error('一次最多克隆100份');exit;
            }
            //取出被克隆的母体
            $row = M('Goods')->where(array('id'=>$id))->find();
            if($row){
                $parent_id = $row['parent_id'] ? $row['parent_id'] : $row['id'];
                //循环克隆$num份样本数据，但是代号是唯一的
                for($i=0;$i<intval($num);$i++){
                    $InstId = D('Goods')->addGoods($row['title'],
                        $row['content'],
                        $row['price'],
                        $row['saleprice'],
                        json_decode($row['img'],true),
                        1,
                        $row['item'],
                        $row['sort'],
                        $row['categray'],
                        $parent_id,
                        $row['deadline']);
                    if($InstId){
                        //生成商品唯一码
                        $sncode = $this->genSNCode($row['sort']);
                        $ret = M('Goods')->where(array('id'=>$InstId))->save(array('sncode'=>$sncode));
                    }
                }
                $this->_success('克隆完成');
            }
        }else{
            $this->_error('克隆失败');
        }
    }
    /**
     * 插入
     * @return [type] [description]
     */
    public function insert(){
        
        do
        {
            //验证
            $picArr = $this->_post('pic');
            $title = $this->_post('title');
            $content = $this->_post('content',"htmlspecialchars");
            $price = $this->_post('price');
            $saleprice = $this->_post('saleprice');
            $item = $this->_post('item');
            $content = stripslashes($content);
            $sort = $this->_post('sort');
            $categray = $this->_post('categray');
            $deadline = $this->_post('deadline');
            if(empty($title)){
                $this->_error('请填写商品标题');break;
            }
            if(empty($price) || empty($saleprice)){
                $this->_error('请填写商品价格');break;
            }
            if(empty($picArr)){
                $this->_error('请上传商品图片');break;
            }
            if(empty($deadline)){
                $this->_error('请填写商品领取截止日期');break;
            }
            /*//组装
            $data['title'] = $title;
            $data['content'] = $content;
            $data['price'] = $price;
            $data['saleprice'] = $saleprice;
            $data['img'] = json_encode($picArr);
            $data['status'] = 1;
            $data['item'] = $item;
            $data['sort'] = $sort;
            $data['create_time'] = $data['update_time'] = time();
            //入库
            $InstId = M('Goods')->add($data);*/
            $InstId = D('Goods')->addGoods($title,$content,$price,$saleprice,$picArr,1,$item,$sort,$categray,0,strtotime($deadline));
            if($InstId) {
                //生成商品唯一码
                $sncode = $this->genSNCode($sort);
                $ret = M('Goods')->where(array('id'=>$InstId))->save(array('sncode'=>$sncode));
            }else {
                $ret = false;
            }
            return $ret;break;
        }while ( true) ;
        
    }
    /**
     * 更新
     * @return [type] [description]
     */
    public function update(){
        $data =array();
        $id = $this->_post('id',0);
        if($id){
            do
            {
                //验证
                $picArr = $this->_post('pic');
                $title = $this->_post('title');
                $content = $this->_post('content','htmlspecialchars');
                $price = $this->_post('price');
                $saleprice = $this->_post('saleprice');
                $item = $this->_post('item');
                $sort = $this->_post('sort');
                $content = stripslashes($content);
                if(empty($title)){
                    $this->_error('请填写商品标题');break;
                }
                if(empty($price) || empty($saleprice)){
                    $this->_error('请填写商品价格');break;
                }
                if(empty($picArr)){
                    $this->_error('请上传商品图片');break;
                }
                $data['title'] = $title;
                $data['content'] = $content;
                $data['price'] = $price;
                $data['saleprice'] = $saleprice;
                $data['item'] = $item;
                $data['img'] = json_encode($picArr);
                $data['sort'] = $sort;
                $data['update_time'] = time();

                $re = M('Goods')->where(array('id'=>$id))->save($data);
                break;
            }while(true);
            
        }else{
            $re = false;
        }
        return $re;
        
    }
    public function edit()
    {
        $id = $this->_get('id',0);
        $row = M('Goods')->where(array('id'=>$id))->find();
        if($row){
//            $this->assign('sortarr',D('Goods')->getSortarr());
            $this->assign('data',$row);
            $this->display('set');
        }else{
            $this->_error('不存在此商品');
        }
    }

    /**
     * 统计
     */
    public function statis()
    {
        $good_model = D('Goods');
        $sort = $good_model->getSortarr();

        //1、总商品数，各分类商品数
        $map = array();
        $total = $good_model->getGoodsCount($map);
        foreach ($sort as $key => $val) {
            $map['sort'] = $key;
            $total_sort[$key] = $good_model->getGoodsCount($map);
        }

        //2、配送商品数，各分类配送数，总金额
        unset($map);
        $map['issend'] = 1;
        $total_send = $good_model->getGoodsCount($map);
        $sum_send = $good_model->getGoodsSum($map);
        foreach ($sort as $key => $val) {
            $map['sort'] = $key;
            $total_send_sort[$key] = $good_model->getGoodsCount($map);
            $sum_send_sort[$key] = $good_model->getGoodsSum($map);
        }

        //2.5、未配送商品数，各分类配送数，总金额
        unset($map);
        $map['issend'] = 0;
        $total_unsend = $good_model->getGoodsCount($map);
        $sum_unsend = $good_model->getGoodsSum($map);
        foreach ($sort as $key => $val) {
            $map['sort'] = $key;
            $total_unsend_sort[$key] = $good_model->getGoodsCount($map);
            $sum_unsend_sort[$key] = $good_model->getGoodsSum($map);
        }

        //3、本周配送商品数，各分类配送数，总金额
        unset($map);
        $aweek = time()-((date('w')==0?7:date('w'))-1)*86400; //本周一时间戳
        $map['issend'] = 1;
        $map['send_time'] = array('gt',$aweek);
        $total_week_send = $good_model->getGoodsCount($map);
        $sum_week_send = $good_model->getGoodsSum($map);
        foreach ($sort as $key => $val) {
            $map['sort'] = $key;
            $total_week_send_sort[$key] = $good_model->getGoodsCount($map);
            $sum_week_send_sort[$key] = $good_model->getGoodsSum($map);
        }

        //4、本季度配送商品数，各分类配送数，总金额
        unset($map);
        $aquarter = mktime(0, 0, 0,date('n')-(date('n')-1)%3,1,date('Y')); //本季度时间戳
        $map['issend'] = 1;
        $map['send_time'] = array('gt',$aquarter);
        $total_quarter_send = $good_model->getGoodsCount($map);
        $sum_quarter_send = $good_model->getGoodsSum($map);
        foreach ($sort as $key => $val) {
            $map['sort'] = $key;
            $total_quarter_send_sort[$key] = $good_model->getGoodsCount($map);
            $sum_quarter_send_sort[$key] = $good_model->getGoodsSum($map);
        }

        $this->assign('sort',$sort);
        $this->assign('all',array('total'=>$total,'sortTotal'=>$total_sort));
        $this->assign('send',array('total'=>$total_send,'sortTotal'=>$total_send_sort,'sum'=>$sum_send,'sortSum'=>$sum_send_sort));
        $this->assign('unsend',array('total'=>$total_unsend,'sortTotal'=>$total_unsend_sort,'sum'=>$sum_unsend,'sortSum'=>$sum_unsend_sort));
        $this->assign('aweek',array('total'=>$total_week_send,'sortTotal'=>$total_week_send_sort,'sum'=>$sum_week_send,'sortSum'=>$sum_week_send_sort));
        $this->assign('aquarter',array('total'=>$total_quarter_send,'sortTotal'=>$total_quarter_send_sort,'sum'=>$sum_quarter_send,'sortSum'=>$sum_quarter_send_sort));

        $this->display();
    }

    public function export()
    {
        $parameters = I('parameters','','urldecode');
        $parameters = json_decode(stripslashes($parameters),true);
        $map = array();
        //----------------------------------------准备数据--------------------------------------
        switch ($parameters['type']) {
            case '1':
                $map['sncode'] = $parameters['keywords'];
                break;
            case '2':
                $map['title'] = array('like', '%'.$parameters['keywords'].'%');
                break;
            default:
                break;
        }
        if(isset($parameters['sort']) &&  $parameters['sort']!='') {
            $map['sort'] = intval($parameters['sort']);
        }

        //分类
        $sortArr = D('Goods')->getSortarr();
        
        $limit = 1000;
        $data = M('Goods')->where($map)->limit($limit)->order('id desc')->select();

        //商品总数
        $dataNum = count($data);

        //----------------------------------------导出开始--------------------------------------
        Vendor('PHPExcel.PHPExcel');
        // Vendor('PHPExcel.PHPExcel.IOFactory');
        $objPHPExcel = new PHPExcel();
        
                // Set document properties
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                                     ->setLastModifiedBy("Maarten Balliauw")
                                     ->setTitle("Office 2007 XLSX Test Document")
                                     ->setSubject("Office 2007 XLSX Test Document")
                                     ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                                     ->setKeywords("office 2007 openxml php")
                                     ->setCategory("Test result file");
        $filename = "商品清单.xls";

        
        // Add some data
        $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A1', '商品码')
                    ->setCellValue('B1', '商品名称')
                    ->setCellValue('C1', '分类')
                    ->setCellValue('D1', '市场价')
                    ->setCellValue('E1', '促销价')
                    ->setCellValue('F1', '发布时间');

        for ($i=0; $i < $dataNum; $i++) {
            $row = $data[$i]; 
            $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . ($i+2), $row['sncode'])
                    ->setCellValue('B' . ($i+2), $row['title'])
                    ->setCellValue('C' . ($i+2), $sortArr[$row['sort']])
                    ->setCellValue('D' . ($i+2), $row['price'])
                    ->setCellValue('E' . ($i+2), $row['saleprice'])
                    ->setCellValue('F' . ($i+2), date('Y-m-d H:i:s',$row['create_time']));
        }
       
        // Rename worksheet
        // $objPHPExcel->getActiveSheet()->setTitle('sheet0');
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); 
        //$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(60);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true); 
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type: application/vnd.ms-excel;");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition:attachment;filename=".$filename);
        header("Content-Transfer-Encoding:binary");
        

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit();
    }

    public function test(){
        $d = D('Goods')->getGoods(array(),0,100);
        ECHO D('Goods')->getLastSql();
        var_dump($d);
    }

    public function uploadImg()
    {
        import("ORG.Net.UploadFile");
         //导入上传类
        $upload = new UploadFile();
         //设置上传文件大小
        $upload->maxSize = 3292200;
         //设置上传文件类型
        $upload->allowExts = explode(',', 'jpg,gif,png,jpeg');
         //设置附件上传目录
        $upload->savePath = './Uploads/';
         //设置需要生成缩略图，仅对图像文件有效
        $upload->thumb = true;
         // 设置引用图片类库包路径
        //$upload->imageClassPath = '@.ORG.Image';
         //设置需要生成缩略图的文件后缀
        $upload->thumbPrefix = 'm_';  //生产2张缩略图
         //设置缩略图最大宽度
        $upload->thumbMaxWidth = '400';
         //设置缩略图最大高度
        $upload->thumbMaxHeight = '400';
         //设置上传文件规则
        $upload->saveRule = 'uniqid';
         //删除原图
        //$upload->thumbRemoveOrigin = true;
         if (!$upload->upload()) {
            //捕获上传异常
            $re = array('status'=>'400','data'=>array(),'msg'=>'上传错误');
         } else {
            //取得成功上传的文件信息
            $uploadList = $upload->getUploadFileInfo();
            /*import("@.ORG.Image");
            //给m_缩略图添加水印, Image::water('原文件名','水印图片地址')
            Image::water($uploadList[0]['savepath'] . 'm_' . $uploadList[0]['savename'], APP_PATH.'Tpl/Public/Images/logo.png');
            $_POST['image'] = $uploadList[0]['savename'];*/
            foreach ($uploadList as $key => $value) {
                $retUpload[] = '/Uploads/' . $value['savename'];
            }
            $re = array('status'=>'200','data'=>$retUpload[0],'msg'=>'');
         }
         echo json_encode($re);exit;
    }

    /**
     * 编辑器上传
     * @return [type] [description]
     */
    public function editorUpload()
    {
        //logger('-start-');
        $img = $this->upload();
        if($img){
            echo "{'url':'" .getImgPath($img[0]) . "','title':'default','original':'default','state':'SUCCESS'}";
        }else{
            echo "{'url':'','title':'0','original':'0','state':'0'}";
        }
        exit;
    }
    /**
     * 生成SN码
     * @return [type] [description]
     */
    private function genSNCode($sort)
    {
        /*$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $sCode = D('Goods')->getSortArrCode();
        //$yCode[intval(date('Y')) - 2011]
        $orderSn = $sCode[$sort] .
                strtoupper(dechex(date('m'))) . date('d') . 
                substr(time(), -5) . substr(microtime(), 2, 5) . 
                sprintf('%02d', rand(0, 99));
        return $orderSn;*/
        $str_chr = chr(rand(97,122));
        $str_num = mt_rand(10000, 99999);
        $uniqid = md5(uniqid());
        $unq_compile = substr($uniqid, 0,6) . substr($uniqid, -6);
 
        return $str_chr.$unq_compile.$str_num;
    }
}